package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.RecordTaskDao;
import jumpingnotes.model.entity.RecordTask;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

public class RecordTaskHibernateDao extends GenericHibernateDao<RecordTask> implements RecordTaskDao
{
	public RecordTaskHibernateDao()
	{
		super(RecordTask.class);
	}

	@SuppressWarnings("unchecked")
	public List<RecordTask> findRecordTaskByRecordAlbumId(final int recordAlbumId, final int firstResult,
			final int maxResults)
	{
		return (List<RecordTask>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct rt from RecordTask rt where rt.recordAlbum.recordAlbumId=:recordAlbumId");
				query.setInteger("recordAlbumId", recordAlbumId);

				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);

				return query.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<RecordTask> findRecordTaskByChapterId(final int chapterId, final int firstResult, final int maxResults)
	{
		return (List<RecordTask>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct rt from RecordTask rt where rt.chapter.chapterId=:chapterId");
				query.setInteger("chapterId", chapterId);

				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);

				return query.list();
			}
		});
	}

	public boolean checkRecordTaskUnique(final int chapterId, final int recordAlbumId)
	{
		return (Boolean) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct rt from RecordTask rt where rt.chapter.chapterId=:chapterId and rt.recordAlbum.recordAlbumId=:recordAlbumId");
				query.setInteger("chapterId", chapterId);
				query.setInteger("recordAlbumId", recordAlbumId);

				return query.list().size() == 1;
			}
		});
	}
}
